import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { usePermissionStore } from '@/stores/permission';
import { staticRoutes, layoutRoute, authRoutes } from './routes'

const router = createRouter({
  history: createWebHistory(),
  routes: [...staticRoutes, layoutRoute],  // 包含基础布局路由
  scrollBehavior: () => ({ top: 0 })
});

const whiteList = ['/login', '/404', '/front']; // 新增白名单定义

// 启用路由守卫
router.beforeEach(async (to) => {
  const userStore = useUserStore();
  
  

  // 白名单直接放行
  if (whiteList.includes(to.path)) return true;
  
  // 未登录处理
  if (!userStore.token) {
    return `/login?redirect=${encodeURIComponent(to.fullPath)}`;
  }

  // 已登录但未获取用户信息
  if (!userStore.roles.length) {
    try {
      const infoRes = await api.user.getInfo();
      userStore.roles = infoRes.data.roles;
    } catch (error) {
      userStore.logout();
      return '/login';
    }
  }

  // 动态添加权限路由（只执行一次）
  if (!router.hasRoute('Dashboard')) {  // 通过路由名称判断是否已添加
    if (userStore.roles.some(role => ['admin', 'editor'].includes(role))) {
      authRoutes.forEach(route => {
        router.addRoute('layoutRoute', route);  // 将权限路由添加到基础布局下
      });
    }
    
    // 添加404路由兜底
    router.addRoute({
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    });

    return to.fullPath;  // 重新导航
  }

  return true;
});

export default router;